<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="140px">
      <el-form-item label="工厂id" prop="companyId">
        <el-input
          v-model="queryParams.companyId"
          placeholder="请输入工厂id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工厂名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入工厂名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型名称" prop="mainEquipmentTypeId">
        <el-input
          v-model="queryParams.mainEquipmentTypeId"
          placeholder="请输入设备类型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="变量名称" prop="variableName">
        <el-input
          v-model="queryParams.variableName"
          placeholder="请输入变量名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="变量英文名称" prop="variableEnName">
        <el-input
          v-model="queryParams.variableEnName"
          placeholder="请输入变量英文名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="变量所属区域" prop="area">
        <el-input
          v-model="queryParams.area"
          placeholder="请输入变量所属区域"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="变量来源" prop="valueSource">
        <el-input
          v-model="queryParams.valueSource"
          placeholder="请输入变量来源"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="变量当前值" prop="variableValue">
        <el-input
          v-model="queryParams.variableValue"
          placeholder="请输入变量当前值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="变量允许的最小值" prop="minValue">
        <el-input
          v-model="queryParams.minValue"
          placeholder="请输入变量允许的最小值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="变量允许的最大值" prop="maxValue">
        <el-input
          v-model="queryParams.maxValue"
          placeholder="请输入变量允许的最大值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="变量最后更新时间戳" prop="updateTimestamp">
        <el-date-picker clearable
          v-model="queryParams.updateTimestamp"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择变量最后更新时间戳">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="变量值的精度" prop="accuracy">
        <el-input
          v-model="queryParams.accuracy"
          placeholder="请输入变量值的精度"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="变量值的单位" prop="unit">
        <el-input
          v-model="queryParams.unit"
          placeholder="请输入变量值的单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['deviceInfo:variables:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['deviceInfo:variables:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['deviceInfo:variables:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['deviceInfo:variables:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="variablesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工厂id" align="center" prop="companyId" />
      <el-table-column label="工厂名称" align="center" prop="companyName" />
      <el-table-column label="关联的设备类型ID" align="center" prop="mainEquipmentTypeId" />
      <el-table-column label="主设备类型" align="center" prop="mainEquipmentTypeName" />
      <el-table-column label="关联的设备类型ID" align="center" prop="secondaryEquipmentTypeId" />
      <el-table-column label="次级设备类型" align="center" prop="secondaryEquipmentTypeName" />
      <el-table-column label="变量名称" align="center" prop="variableName" />
      <el-table-column label="变量英文名称" align="center" prop="variableEnName" />
      <el-table-column label="变量所属区域" align="center" prop="area" />
      <el-table-column label="变量来源" align="center" prop="valueSource" />
      <el-table-column label="变量当前值" align="center" prop="variableValue" />
      <el-table-column label="变量描述" align="center" prop="description" />
      <el-table-column label="变量允许的最小值" align="center" prop="minValue" />
      <el-table-column label="变量允许的最大值" align="center" prop="maxValue" />
      <el-table-column label="变量最后更新时间戳" align="center" prop="updateTimestamp" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTimestamp, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="变量值的精度" align="center" prop="accuracy" />
      <el-table-column label="变量值的单位" align="center" prop="unit" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['deviceInfo:variables:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['deviceInfo:variables:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改存储设备变量参数信息的对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工厂id" prop="companyId" >
          <el-input disabled v-model="form.companyId" placeholder="请输入工厂id" />
        </el-form-item>
        <el-form-item label="工厂名称" prop="companyName">
          <!-- <el-input v-model="form.companyName" placeholder="请输入工厂名称" /> -->
          <el-select v-model="form.companyName" placeholder="请选择" @focus="getDeptList()" @change="onDeptChange()">
              <el-option v-for="item in deptList" :label="item.deptName" :value="item.deptName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型ID" prop="mainEquipmentTypeId">
          <el-input v-model="form.mainEquipmentTypeId" disabled placeholder="请输入关联的设备类型ID，外键指向equipment_types表" />
        </el-form-item>
        <el-form-item label="设备类型名称" prop="mainEquipmentTypeId">
          <!-- <el-input v-model="form.mainEquipmentTypeName" placeholder="请输入设备类型名称" /> -->
          <el-select v-model="form.mainEquipmentTypeName" placeholder="请选择" @focus="getTypesList(1)" @change="onDeviceChange('main')">
              <el-option v-for="item in typesList" :key="item.equipmentTypeName" :label="item.equipmentTypeName" :value="item.equipmentTypeName"></el-option>
          </el-select>
          <!-- <el-autocomplete
            v-model="form.mainEquipmentTypeName"
            :fetch-suggestions="getTypesList"
            placeholder="Please input"
            @select="handleSelect"
          /> -->

        </el-form-item>
        <el-form-item label="设备类型ID" prop="secondaryEquipmentTypeId">
          <el-input v-model="form.secondaryEquipmentTypeId" disabled placeholder="设备类型ID" />
        </el-form-item>
        <el-form-item label="设备类型名称" prop="secondaryEquipmentTypeId">
          <el-select v-model="form.secondaryEquipmentTypeName" placeholder="请选择" @focus="getTypesList(2)"  @change="onDeviceChange('sec')">
              <el-option v-for="item in typesList" :key="item.equipmentTypeName" :label="item.equipmentTypeName" :value="item.equipmentTypeName"></el-option>
          </el-select>
          <!-- <el-input v-model="form.secondaryEquipmentTypeName" placeholder="请输入设备类型名称" /> -->
        </el-form-item>
        <el-form-item label="变量名称" prop="variableName">
          <el-input v-model="form.variableName" placeholder="请输入变量名称" />
        </el-form-item>
        <el-form-item label="变量英文名称" prop="variableEnName">
          <el-input v-model="form.variableEnName" placeholder="请输入变量英文名称" />
        </el-form-item>
        <el-form-item label="变量所属区域" prop="area">
          <el-input v-model="form.area" placeholder="请输入变量所属区域" />
        </el-form-item>
        <el-form-item label="变量来源" prop="valueSource">
          <el-input v-model="form.valueSource" placeholder="请输入变量来源" />
        </el-form-item>
        <el-form-item label="变量当前值" prop="variableValue">
          <el-input v-model="form.variableValue" placeholder="请输入变量当前值" />
        </el-form-item>
        <el-form-item label="变量描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="变量允许的最小值" prop="minValue">
          <el-input v-model="form.minValue" placeholder="请输入变量允许的最小值" />
        </el-form-item>
        <el-form-item label="变量允许的最大值" prop="maxValue">
          <el-input v-model="form.maxValue" placeholder="请输入变量允许的最大值" />
        </el-form-item>
        <el-form-item label="变量最后更新时间戳" prop="updateTimestamp">
          <el-date-picker clearable
            v-model="form.updateTimestamp"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择变量最后更新时间戳">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="变量值的精度" prop="accuracy">
          <el-input v-model="form.accuracy" placeholder="请输入变量值的精度" />
        </el-form-item>
        <el-form-item label="变量值的单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入变量值的单位" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVariables, getVariables, delVariables, addVariables, updateVariables } from "@/api/deviceInfo/variables";
import { listTypes} from "@/api/deviceInfo/types";
import { listDept} from "@/api/system/dept";


export default {
  name: "Variables",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      defaultParentId: 14,
      // 存储设备变量参数信息的表格数据
      variablesList: [],


      typesList: [],
      deptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        companyName: null,
        mainEquipmentTypeId: null,
        mainEquipmentTypeName: null,
        secondaryEquipmentTypeId: null,
        secondaryEquipmentTypeName: null,
        variableName: null,
        variableEnName: null,
        area: null,
        valueSource: null,
        variableValue: null,
        description: null,
        minValue: null,
        maxValue: null,
        updateTimestamp: null,
        accuracy: null,
        unit: null
      },
      queryTypesParams: {
        parentEquipmentTypeId: null,
        equipmentTypeName: null,
        description: null,
        manufacturer: null,
        installationDate: null,
        maintenanceStatus: null,
        warrantyPeriod: null,
        location: null
      },
      // 表单参数
      form: {

      },
      // 表单校验
      rules: {
        variableName: [
          { required: true, message: "变量名称不能为空", trigger: "blur" }
        ],
      },
      // const state = ref('')

      // interface LinkItem {
      //   value: string
      //   link: string
      // }

      // const links = ref<LinkItem[]>([])

      // const loadAll = () => {
      //   return [
      //     { value: 'vue', link: 'https://github.com/vuejs/vue' },
      //     { value: 'element', link: 'https://github.com/ElemeFE/element' },
      //     { value: 'cooking', link: 'https://github.com/ElemeFE/cooking' },
      //     { value: 'mint-ui', link: 'https://github.com/ElemeFE/mint-ui' },
      //     { value: 'vuex', link: 'https://github.com/vuejs/vuex' },
      //     { value: 'vue-router', link: 'https://github.com/vuejs/vue-router' },
      //     { value: 'babel', link: 'https://github.com/babel/babel' },
      //   ]
      // }

      // let timeout: ReturnType<typeof setTimeout>
      // const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
      //   const results = queryString
      //     ? links.value.filter(createFilter(queryString))
      //     : links.value

      //   clearTimeout(timeout)
      //   timeout = setTimeout(() => {
      //     cb(results)
      //   }, 3000 * Math.random())
      // }
      // const createFilter = (queryString: string) => {
      //   return (restaurant: LinkItem) => {
      //     return (
      //       restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      //     )
      //   }
      // }

      // const handleSelect = (item: Record<string, any>) => {
      //   console.log(item)
      // }

      // onMounted(() => {
      //   links.value = loadAll()
      // })
    };
  },
  created() {
    this.getList();
  },

  methods: {
    /** 查询存储设备变量参数信息的列表 */
    getList() {
      this.loading = true;
      listVariables(this.queryParams).then(response => {
        this.variablesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTypesList(types) {
      this.loading = true;
      // console.info("typesInfoId:" + typesInfoId)
      if (1===types) {
        this.queryTypesParams.parentEquipmentTypeId = this.defaultParentId
      } else if (2 == types) {
        this.queryTypesParams.parentEquipmentTypeId = this.form.mainEquipmentTypeId
      }

      listTypes(this.queryTypesParams).then(response => {
        // console.log("response:" + this.typesList)
        // console.info("response:" + window.JSON.stringfy(response.data))
        // console.info("response:" + response.data)
        this.typesList = response.data;
        // this.total = response.total;
        this.loading = false;
        // console.info("typesList:" +  window.JSON.stringfy(this.typesList))
      });
    },
    onDeviceChange(type) {
      // console.info("typesList:")
      // console.info(this.typesList)

      var item = {}
      if (type == "main") {
        item = this.typesList.find(item1 => item1.equipmentTypeName === this.form.mainEquipmentTypeName)
        this.form.mainEquipmentTypeId = item.equipmentTypeId
      } else if (type == "sec") {

        // console.log(111111111111)

        // console.log(this.form.secondaryEquipmentTypeName)
        item = this.typesList.find(item1 => item1.equipmentTypeName === this.form.secondaryEquipmentTypeName)
        this.form.secondaryEquipmentTypeId = item.equipmentTypeId
      }
      // console.log("item:")
      // console.log(item)
      // console.log("form:")
      // console.log(this.form)
    },
    getDeptList(types) {
      this.loading = true;
      // console.info("typesInfoId:" + typesInfoId)

      listDept(null).then(response => {
        // console.log("response:" + this.typesList)
        // console.info("response:" + window.JSON.stringfy(response.data))
        // console.info("response:" + response.data)
        this.deptList = response.data;
        // this.total = response.total;
        this.loading = false;
        // console.info("typesList:" +  window.JSON.stringfy(this.typesList))
      });
    },
    onDeptChange() {
      // console.info("typesList:")
      // console.info(this.typesList)
      var item = {}
      item = this.deptList.find(item1 => item1.deptName === this.form.companyName)
      this.form.companyId = item.deptId

      // console.log("item:")
      // console.log(item)
      // console.log("form:")
      // console.log(this.form)
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        variableId: null,
        companyId: null,
        companyName: null,
        mainEquipmentTypeId: null,
        mainEquipmentTypeName: null,
        secondaryEquipmentTypeId: null,
        secondaryEquipmentTypeName: null,
        variableName: null,
        variableEnName: null,
        area: null,
        valueSource: null,
        variableValue: null,
        description: null,
        minValue: null,
        maxValue: null,
        updateTimestamp: null,
        accuracy: null,
        unit: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.variableId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加存储设备变量参数信息的";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const variableId = row.variableId || this.ids
      getVariables(variableId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改存储设备变量参数信息的";
      });
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.variableId != null) {
            console.log(this.form)
            updateVariables(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVariables(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const variableIds = row.variableId || this.ids;
      this.$modal.confirm('是否确认删除存储设备变量参数信息的编号为"' + variableIds + '"的数据项？').then(function() {
        return delVariables(variableIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('deviceInfo/variables/export', {
        ...this.queryParams
      }, `variables_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
